package libs

import (
	"crypto/hmac"
	"crypto/sha256"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"time"
)

// 生成token
func CreateAccessToken(id int, expireIn int) string {
	timestamp := time.Now().Unix()
	hash := hmac.New(sha256.New, []byte(config.Token))
	hash.Write([]byte(fmt.Sprintf("%d.%s%d", id, RandomStr(8), timestamp)))

	token := fmt.Sprintf("%x", hash.Sum(nil))

	err := RedisSet("access_token:"+token, id, expireIn)
	if err != nil {
		panic(err)
	}

	return token
}

// 校验token是否正确
// 返回id，0为不正确
func CheckAccessToken(token string) int {
	ret, err := RedisGet("access_token:" + token)
	if err != nil {
		panic(err)
	}
	if ret == nil {
		return 0
	}
	data, _ := redis.Int(ret, err)
	// fmt.Printf("%d\n", data)
	return data
}
